$(function () {
    var userName = $("#username").val();
    $.ajax({
        url: "cart/getCart",
        type: "GET",
        data: {userName: userName},
        success: function (res) {
            if (res.code === 0) {
                var shopList = res.data;
                var str = "";
                for (var i = 0; i < shopList.length; i++) {
                    str += `
                    
                    <div class="cartBox"> 
                <div class="shop_info">
                    <div class="all_check">
                        <!--店铺全选-->
                        <input type="checkbox" id="shop_${i}" value="${i}" class="shopChoice">
                        <label for="shop_${i}" class="shop"></label>
                    </div>
                    <div class="shop_name">
                        店铺：<a href="javascript:;">${shopList[i].shopName}</a>
                    </div>
                </div>
                <div class="order_content">                   
                `;
                    var cartShopPros = shopList[i].cartShopPros;

                    for (var j = 0; j < cartShopPros.length; j++) {
                        str += `
                        <input type="hidden" id="" value="${i}"/>       
                <ul class="order_lists">
                    <li class="list_chk">
                        <input type="checkbox"  name="product" id="${cartShopPros[j].id}" value="${cartShopPros[j].id}" class="son_check">
                        <label for="${cartShopPros[j].id}"></label>
                    </li>
                    <li class="list_con">
                        <div class="list_img"><a href="javascript:;"><img src="${cartShopPros[j].productImg}" alt="" width="90px" height="90px"></a></div>
                        <div class="list_text"><a href="javascript:;">${cartShopPros[j].productName}</a></div>
                    </li>
                    <li class="list_info">
                        <p>规格：${cartShopPros[j].specification}</p>
                        <p></p>
                    </li>
                    <li class="list_price">
                        <p class="price">￥${cartShopPros[j].price}</p>
                    </li>
                    <li class="list_amount">
                        <div class="amount_box">
                            <input type="hidden" value="${cartShopPros[j].price}">
                            <input type="hidden" value="${cartShopPros[j].id}">
                            <a href="javascript:;" class="reduce reSty">-</a>                      
                            <input type="text" value="${cartShopPros[j].buySum}" class="sum">                           
                            <a href="javascript:;" class="plus">+</a>                        
                            <input type="hidden" value="${cartShopPros[j].id}">
                            <input type="hidden" value="${cartShopPros[j].price}">
                        </div>
                    </li>
                    <li class="list_sum">
                        <p class="sum_price">￥${cartShopPros[j].sumPrice}</p>
                    </li>
                    <li class="list_op">
                        
                        <p class="del">
                        <input type="hidden" value="${cartShopPros[j].id}">
                        <a href="javascript:;" class="delBtn">移除商品</a>
                        </p>
                    </li>
                </ul>
              `;
                    }
                    str += `</div></div>`;
                }
            }
            $(".cartMain_hd").after(str);
            //获取所有被标记的label标签
            // $(".mark");
            $(".calBtn").click(function () {
                var checkID = [];//定义一个空数组 
                $("input[name='product']:checked").each(function (i) {//把所有被选中的复选框的值存入数组
                    checkID[i] = $(this).val();
                });
                console.log(checkID);
                // console.log($(".sum").val());
                // console.log($(".mark").length);
            });
            //点击数据库数量减1
            $(".reduce").click(function () {
                var num = $(this).next().val();
                var id = $(this).prev().val();
                var price =  $(this).prev().prev().val();
                if (num > 1) {
                    $.ajax({
                        url: "cart/reduceCart",
                        data: {id: id,price: price},
                        type: "post",
                        success: function (res) {
                            if (res.code === 0) {
                                console.log("成功减1");
                            }
                        }
                    });
                    // console.log($(this).prev().val());
                }
            });

            //点击数据库数量加1
            $(".plus").click(function () {
                var id = $(this).next().val()
                var price =  $(this).next().next().val();
                $.ajax({
                    url: "cart/plusCart",
                    data: {id: id,price: price},
                    type: "post",
                    success: function (res) {
                        if (res.code === 0) {
                            console.log("成功加1")
                        }
                    }
                });
                // console.log($(this).next().val());
            });
            // $(":checkbox").on("change",function(){
            //     var $checkbox = $(this);
            //     console.log($checkbox.val());
            //     // console.log($('input:checked').length);
            // });


            //全局的checkbox选中和未选中的样式
            var $allCheckbox = $('input[type="checkbox"]'),     //全局的全部checkbox
                $wholeChexbox = $('.whole_check'),
                $cartBox = $('.cartBox'),                       //每个商铺盒子
                $shopCheckbox = $('.shopChoice'),               //每个商铺的checkbox
                $sonCheckBox = $('.son_check');
            //每个商铺下的商品的checkbox
            $allCheckbox.click(function () {
                if ($(this).is(':checked')) {
                    $(this).next('label').addClass('mark');
                } else {
                    $(this).next('label').removeClass('mark')
                }
            });

            //===============================================全局全选与单个商品的关系================================
            $wholeChexbox.click(function () {
                var $checkboxs = $cartBox.find('input[type="checkbox"]');
                if ($(this).is(':checked')) {
                    $checkboxs.prop("checked", true);
                    $checkboxs.next('label').addClass('mark');
                } else {
                    $checkboxs.prop("checked", false);
                    $checkboxs.next('label').removeClass('mark');
                }
                totalMoney();
            });


            $sonCheckBox.each(function () {
                $(this).click(function () {
                    if ($(this).is(':checked')) {
                        //判断：所有单个商品是否勾选
                        var len = $sonCheckBox.length;
                        var num = 0;
                        $sonCheckBox.each(function () {
                            if ($(this).is(':checked')) {
                                num++;
                            }
                        });
                        if (num == len) {
                            $wholeChexbox.prop("checked", true);
                            $wholeChexbox.next('label').addClass('mark');
                        }
                    } else {
                        //单个商品取消勾选，全局全选取消勾选
                        $wholeChexbox.prop("checked", false);
                        $wholeChexbox.next('label').removeClass('mark');
                    }
                })
            })

            //=======================================每个店铺checkbox与全选checkbox的关系/每个店铺与其下商品样式的变化===================================================

            //店铺有一个未选中，全局全选按钮取消对勾，若店铺全选中，则全局全选按钮打对勾。
            $shopCheckbox.each(function () {
                $(this).click(function () {
                    if ($(this).is(':checked')) {
                        //判断：店铺全选中，则全局全选按钮打对勾。
                        var len = $shopCheckbox.length;
                        var num = 0;
                        $shopCheckbox.each(function () {
                            if ($(this).is(':checked')) {
                                num++;
                            }
                        });
                        if (num == len) {
                            $wholeChexbox.prop("checked", true);
                            $wholeChexbox.next('label').addClass('mark');
                        }

                        //店铺下的checkbox选中状态
                        $(this).parents('.cartBox').find('.son_check').prop("checked", true);
                        $(this).parents('.cartBox').find('.son_check').next('label').addClass('mark');
                    } else {
                        //否则，全局全选按钮取消对勾
                        $wholeChexbox.prop("checked", false);
                        $wholeChexbox.next('label').removeClass('mark');

                        //店铺下的checkbox选中状态
                        $(this).parents('.cartBox').find('.son_check').prop("checked", false);
                        $(this).parents('.cartBox').find('.son_check').next('label').removeClass('mark');
                    }
                    totalMoney();
                });
            });


            //========================================每个店铺checkbox与其下商品的checkbox的关系======================================================

            //店铺$sonChecks有一个未选中，店铺全选按钮取消选中，若全都选中，则全选打对勾
            $cartBox.each(function () {
                var $this = $(this);
                var $sonChecks = $this.find('.son_check');
                $sonChecks.each(function () {
                    $(this).click(function () {
                        if ($(this).is(':checked')) {
                            //判断：如果所有的$sonChecks都选中则店铺全选打对勾！
                            var len = $sonChecks.length;
                            var num = 0;
                            $sonChecks.each(function () {
                                if ($(this).is(':checked')) {
                                    num++;
                                }
                            });
                            if (num == len) {
                                $(this).parents('.cartBox').find('.shopChoice').prop("checked", true);
                                $(this).parents('.cartBox').find('.shopChoice').next('label').addClass('mark');
                            }

                        } else {
                            //否则，店铺全选取消
                            $(this).parents('.cartBox').find('.shopChoice').prop("checked", false);
                            $(this).parents('.cartBox').find('.shopChoice').next('label').removeClass('mark');
                        }
                        totalMoney();
                    });
                });
            });


            //=================================================商品数量==============================================
            var $plus = $('.plus'),
                $reduce = $('.reduce'),
                $all_sum = $('.sum');
            $plus.click(function () {
                var $inputVal = $(this).prev('input'),
                    $count = parseInt($inputVal.val()) + 1,
                    $obj = $(this).parents('.amount_box').find('.reduce'),
                    $priceTotalObj = $(this).parents('.order_lists').find('.sum_price'),
                    $price = $(this).parents('.order_lists').find('.price').html(),  //单价
                    $priceTotal = $count * parseFloat($price.substring(1));
                $inputVal.val($count);
                $priceTotalObj.html('￥' + $priceTotal);
                if ($inputVal.val() > 1 && $obj.hasClass('reSty')) {
                    $obj.removeClass('reSty');
                }
                totalMoney();
            });

            $reduce.click(function () {
                var $inputVal = $(this).next('input'),
                    $count = parseInt($inputVal.val()) - 1,
                    $priceTotalObj = $(this).parents('.order_lists').find('.sum_price'),
                    $price = $(this).parents('.order_lists').find('.price').html(),  //单价
                    $priceTotal = $count * parseFloat($price.substring(1));
                if ($inputVal.val() > 1) {
                    $inputVal.val($count);
                    $priceTotalObj.html('￥' + $priceTotal);
                }
                if ($inputVal.val() == 1 && !$(this).hasClass('reSty')) {
                    $(this).addClass('reSty');
                }
                totalMoney();
            });

            $all_sum.keyup(function () {
                var $count = 0,
                    $priceTotalObj = $(this).parents('.order_lists').find('.sum_price'),
                    $price = $(this).parents('.order_lists').find('.price').html(),  //单价
                    $priceTotal = 0;
                if ($(this).val() == '') {
                    $(this).val('1');
                }
                $(this).val($(this).val().replace(/\D|^0/g, ''));
                $count = $(this).val();
                $priceTotal = $count * parseInt($price.substring(1));
                $(this).attr('value', $count);
                $priceTotalObj.html('￥' + $priceTotal);
                totalMoney();
            })

            //======================================移除商品========================================

            var $order_lists = null;
            var $order_content = '';
            var ids;
            $('.delBtn').click(function () {
                $order_lists = $(this).parents('.order_lists');
                $order_content = $order_lists.parents('.order_content');
                $('.model_bg').fadeIn(300);
                $('.my_model').fadeIn(300);
                var deleteId = $(this).prev().val();
                id = deleteId;
                // console.log(id);
                //确定按钮，移除商品
                $('.dialog-sure').click(function () {
                    $order_lists.remove();
                    if ($order_content.html().trim() == null || $order_content.html().trim().length == 0) {
                        $order_content.parents('.cartBox').remove();
                    }
                    closeM();
                    $sonCheckBox = $('.son_check');
                    totalMoney();
                    console.log(id);
                    //ajax从数据中移除数据
                    $.ajax({
                        url: "cart/deleteCart",
                        data: {id: id},
                        type: "POST",
                        success: function (res) {
                            console.log("删除成功");
                            window.location.reload();
                        }
                    });

                })
            });
            console.log();
            //关闭模态框
            $('.closeModel').click(function () {
                closeM();
            });
            $('.dialog-close').click(function () {
                closeM();
            });

            function closeM() {
                $('.model_bg').fadeOut(300);
                $('.my_model').fadeOut(300);
            }


            //======================================总计==========================================

            function totalMoney() {
                var total_money = 0;
                var total_count = 0;
                var calBtn = $('.calBtn a');
                $sonCheckBox.each(function () {
                    if ($(this).is(':checked')) {
                        var goods = parseInt($(this).parents('.order_lists').find('.sum_price').html().substring(1));
                        var num = parseInt($(this).parents('.order_lists').find('.sum').val());
                        total_money += goods;
                        total_count += num;
                    }
                });
                $('.total_text').html('￥' + total_money);
                $('.piece_num').html(total_count);

                // console.log(total_money,total_count);

                if (total_money != 0 && total_count != 0) {
                    if (!calBtn.hasClass('btn_sty')) {
                        calBtn.addClass('btn_sty');
                    }
                } else {
                    if (calBtn.hasClass('btn_sty')) {
                        calBtn.removeClass('btn_sty');
                    }
                }
            }
        }
    });
});